package com.jthink.module.menu;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.jfinal.aop.Inject;
import com.jthink.common.model.ArticleCategory;
import com.jthink.common.model.Menu;
import com.jthink.module.article.ArticleCategoryService;
import com.jthink.module.common.MenuContext;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class MenuService {
    private final Menu dao = new Menu().dao();
    @Inject
    ArticleCategoryService articleCategoryService;
    private ArticleCategory categoryDao = new ArticleCategory().dao();

    public Menu getById(Integer id) {
        return dao.findById(id);
    }

    public List<Menu> list(String type) {
        return dao.find("SELECT * FROM menu where menuType=? order by weight desc", type);
    }

    public Stack<Menu> getMenuStack(Menu menu) {
        // 返回面包屑导航
        Stack<Menu> menuStack = new Stack<Menu>();
        setMenuStack(menu, menuStack);
        return menuStack;
    }

    public List<Menu> getBreadcrumb() {
        Menu menu = MenuContext.get();
        Stack<Menu> stack = getMenuStack(menu);
        List<Menu> breadcrumb = new LinkedList<Menu>();
        while (!stack.empty()) {
            breadcrumb.add(stack.pop());
        }
        return breadcrumb;
    }

    public void setMenuStack(Menu menu, Stack<Menu> stack) {
        stack.push(menu);
        if (null != menu && menu.getPid() > 0) {
            Menu parentMenu = this.getById(menu.getPid());
            setMenuStack(parentMenu, stack);
        }
    }

    public boolean setActiveMenu(String idOrslug, List<Tree<Object>> menus) {
        boolean success = false;
        for (Tree<Object> tree : menus) {
            String url = tree.get("url").toString();
            // 按url地址匹配一下
            if (url.indexOf("/" + idOrslug) > -1 || url.indexOf("/article/" + idOrslug) > -1 || url.indexOf("/article/category/" + idOrslug) > -1 ||url.indexOf("/article/tag/" + idOrslug) > -1 || url.indexOf("/page/" + idOrslug) > -1) {
                // 当前菜选中菜单上下文
                Menu menu = dao.findById(tree.getId());
                // 把当前菜单放入线程变量中，每个线程隔离开
                MenuContext.set(menu);
                success = true;
                break;
            }

            List<Tree<Object>> children = tree.getChildren();
            if (CollUtil.isNotEmpty(children)) {
                // 递归子菜单
                success = setActiveMenu(idOrslug, children);
            }
        }
        if (!success) {
            ArticleCategory category = articleCategoryService.getBySlug(idOrslug) ;
            if (null!=category && category.getPid() > 0) {
                ArticleCategory parent=categoryDao.findById(category.getPid());
                setActiveMenu(parent.getSlug(), menus);
            }
        }
        return success;
    }
}
